package com.oa.kq.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.entity.Tips;
import com.mdp.core.err.BizException;
import com.mdp.core.query.QueryTools;
import com.mdp.core.service.SequenceService;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.kq.entity.Dept;
import com.oa.kq.entity.Group;
import com.oa.kq.service.DeptService;
import com.oa.kq.service.GroupService;
import com.oa.kq.vo.GroupInfoVo;
import com.oa.utils.ExcelView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月9日
 */
@Controller
@RequestMapping(value = "/*/oa/kq/group")
@Api(tags = {"考勤组表-操作接口"})
public class GroupController {

    static Logger logger = LoggerFactory.getLogger(GroupController.class);

    @Autowired
    private GroupService groupService;

    @Autowired
    private SequenceService seqService;


    @Autowired
    private DeptService deptService;

    /**
     * 跳转到添加考勤组页面 addGroup.html
     */
    @RequestMapping(value = "/addGroup")
    public ModelAndView addGroup() {
        ModelAndView mv = new ModelAndView();
        return mv;
    }

    /**
     * 添加考勤组
     */
    @ResponseBody
    @RequestMapping(value = "/insertGroup")
    public void insertGroup(@RequestBody GroupInfoVo groupInfoVo) {
        groupService.insertGroupInfo(groupInfoVo);
    }

    /**
     * 添加考勤组拓展
     *
     * @author LinYuKun
     * @cdate 2020/1/7 14:43
     */
    @ResponseBody
    @RequestMapping(value = "/insertGroupExt", method = RequestMethod.POST)
    public Result insertGroupExt(@RequestBody GroupInfoVo groupInfoVo) {
        groupService.insertGroupInfoExt(groupInfoVo);
        return Result.ok("成功增加一条数据");
    }

    /**
     * 获取所有考勤组信息
     * 如果该用户为公司老大，那么需要查出所有该公司下的考勤组
     * //该用户为负责人，则只能看到所负责的组。
     *
     * @cdate 2020/1/7 15:43
     * @cauthor LinYuKun
     */
    @ResponseBody
    @RequestMapping(value = "/getGroupInfo")
    public List<Map<String, Object>> getGroupInfo() {
        return groupService.getGroupInfo();
    }

    /**
     * 拓展 getGroupInfo
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getAllGroup", method = RequestMethod.POST)
    public Result getAllGroup(@RequestBody Map<String, Object> params) {
        Map<String, Object> m = new HashMap();
        QueryWrapper<Group> qw = QueryTools.initQueryWrapper(Group.class, params);
        IPage page = QueryTools.initPage(params);
//        PageUtils.startPage(params);// 开始分页
        List<Map<String, Object>> result = new ArrayList();
        if (StringUtils.isEmpty(params.get("branchId"))) {
            throw new BizException("请传递branchId");
        }
        result = groupService.selectListMapByWhere(page, qw, params);
//        PageUtils.responePage(m, result);// 总的记录数目
        return Result.ok("成功").setData(result);
    }

    /**
     * 点击修改规则。获取该考勤组信息。
     * 获取某一个考勤组的信息。
     *
     * @cdate 2020/1/7 16:53
     * @cauthor LinYuKun
     */
    @ResponseBody
    @RequestMapping(value = "/getOneGroupInfo", method = RequestMethod.POST)
    public Result getOneGroupInfo(@RequestBody Group group) {
        return Result.ok("成功").setData(groupService.getOneGroupInfo(group));
    }

    /**
     * 更新考勤组 修改
     */
    @ResponseBody
    @RequestMapping(value = "/updateGroupInfo", method = RequestMethod.POST)
    public Result updateGroupInfo(@RequestBody GroupInfoVo groupInfoVo) {
        groupService.updateGroupInfo(groupInfoVo);
        return Result.ok("修改成功");
    }

    /**
     * 获取其他组的参与部门。用于选择参与部门时，做限制。
     */
    @ResponseBody
    @RequestMapping(value = "/getOtherGroupJoinDept")
    public List<Dept> getOtherGroupJoinDept(String groupId) {
        return groupService.getOtherGroupJoinDept(groupId);
    }

    /**
     * 获取该公司下所有考勤组的参与部门。用于添加考勤组时，选择参与部门，做限制。
     */
    @ResponseBody
    @RequestMapping(value = "/getGroupJoinDept")
    public List<Dept> getGroupJoinDept() {
        return groupService.getGroupJoinDept();
    }

    /**
     * 获取该公司下所有考勤组的参与人员。用于添加考勤组时，选择其他考勤人员，做限制。
     */
    @ResponseBody
    @RequestMapping(value = "/getGroupsMember")
    public List<User> getGroupsMember() {
        return groupService.getGroupsMember();
    }

    /**
     * 获取其他组的所有考勤人员。用于选择考勤人员时。
     */
    @ResponseBody
    @RequestMapping(value = "/getAllOtherMember")
    public List<User> getAllOtherMember(String groupId) {
        return groupService.getAllOtherMember(groupId);
    }


    /**
     * 查看指定考勤组成员页面。groupMemberList.html
     */
    @RequestMapping(value = "/groupMemberList")
    public ModelAndView getAllMember(String groupId) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("memberList", groupService.getAllMember(groupId));
        return mv;
    }

    /**
     * 跳转到规则设置的页面 editGroup.html
     */
    @RequestMapping(value = "/editGroup")
    public ModelAndView editGroup(String groupId) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("groupId", groupId);
        return mv;
    }


    /**
     * 删除考勤组
     *
     * @cdate 2020/1/7 18:30
     * @cauthor LinYuKun
     */
    @ResponseBody
    @RequestMapping(value = "/deleteGroup", method = RequestMethod.POST)
    public Result deleteGroup(@RequestBody Group group) {
        groupService.deleteGroup(group);
        return Result.ok("删除成功");
    }

    /**
     * 查询当前用户所在的考勤组,以及其考勤规则
     * Date:星期几
     *
     * @cdate 2020/1/8 17:26
     * @cauthor LinYuKun
     */
    @ResponseBody
    @RequestMapping(value = "/getGroupByUser")
    public Result getGroupByUser(User user, String date) {
        return Result.ok("查询成功").setData(groupService.getGroupByUser(user, date));
    }

    /**
     * 跳转到查询页面listGroup.jsp
     */
    @RequestMapping(value = "/listGroup")
    public ModelAndView listGroup(@ModelAttribute("group") Group group, BindingResult result, Model model) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("data", group);
        return mv;
    }


    /**
     * 请求需带json后缀,如selectListGroupByPage.json
     * 根据条件查询数据对象列表
     */
    @RequestMapping(value = "/selectListGroupByPage")
    public ModelAndView selectListGroupByPage(@ModelAttribute("group") Group group, BindingResult result, Model model) {
        ModelAndView mv = new ModelAndView();
//        List<Group>	groupList = groupService.selectListByPage(group);	//列出Group列表
        List<Group> groupList = groupService.selectListByWhere(group);
        mv.addObject("data", groupList);
        Tips tips = new Tips("查询成功");
        mv.addObject("tips", tips);
        return mv;
    }


    /**
     * 根据主键删除1条数据
     */
    @RequestMapping(value = "/deleteGroupByPk")
    public ModelAndView deleteGroupByPk(@ModelAttribute("group") Group group, BindingResult result) {
        ModelAndView mv = new ModelAndView();
        Tips tips = new Tips("成功删除一条数据");
        groupService.deleteByPk(group);
        mv.addObject("tips", tips);
        return mv;
    }

    /**
     * 根据主键修改一条数据
     */
    @RequestMapping(value = "/updateGroupByPk")
    public ModelAndView updateGroupByPk(@ModelAttribute("group") Group group, BindingResult result, Model model) {
        ModelAndView mv = new ModelAndView();
        Tips tips = new Tips("成功更新一条数据");
        groupService.updateByPk(group);
        mv.addObject("data", group);
        mv.addObject("tips", tips);
        return mv;
    }


    /**
     * 批量删除
     */
    @RequestMapping(value = "/batchDeleteGroup")
    public ModelAndView batchDeleteGroup(@RequestParam("id[]") String[] id) {
        ModelAndView mv = new ModelAndView();
        Tips tips = new Tips("成功删除" + id.length + "条数据");
        List<Group> list = new ArrayList<Group>();
        for (int i = 0; i < id.length; i++) {
            Group group = new Group();
            group.setId(id[i]);
            list.add(group);
        }
        groupService.batchDelete(list);
        mv.addObject("tips", tips);
        return mv;
    }

    /*
     * 导出到excel
     * @return
     */
    @RequestMapping(value = "/exportGroupToExcel")
    public ModelAndView exportGroupToExcel(@ModelAttribute("group") Group group, BindingResult result, Model model) {
        ModelAndView mv = new ModelAndView();
        Tips tips = new Tips("成功导出数据");
        try {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            List<String> titles = new ArrayList<String>();
            titles.add("编号id");
            titles.add("组名");
            titles.add("考勤方式012（固定，排班，自由）");
            titles.add("是否允许外勤打卡（0不允许1允许)");
            dataMap.put("titles", titles);
            List<Group> GroupList = groupService.selectListByWhere(group);
            List<Map<String, Object>> allList = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < GroupList.size(); i++) {
                Map<String, Object> row = new HashMap<String, Object>();
                row.put("var1", GroupList.get(i).getId());
                row.put("var2", GroupList.get(i).getGroupName());
                row.put("var3", GroupList.get(i).getKqType());
                row.put("var4", GroupList.get(i).getIsOut());
                allList.add(row);
            }
            dataMap.put("varList", allList);
            ExcelView erv = new ExcelView();
            mv = new ModelAndView(erv, dataMap);
        } catch (Exception e) {
            logger.error(e.toString(), e);
            tips.setErrMsg("导出数据异常");
        }
        mv.addObject("tips", tips);
        return mv;
    }

    @RequestMapping("/getGroupByPage")
    @ResponseBody
    public Result getGroupByPage(@RequestParam Map<String, Object> params) {
        return Result.ok("成功").setData(groupService.getGroupByPage(params));
    }

    @ResponseBody
    @ApiOperation(value = "考勤组表-查询列表", notes = " ")
    @ApiEntityParams(Group.class)
    @ApiResponses({@ApiResponse(code = 200, response = Group.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listGroup(@ApiIgnore @RequestParam Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        QueryWrapper<Group> qw = QueryTools.initQueryWrapper(Group.class, params);
        IPage page = QueryTools.initPage(params);
        List<Map<String, Object>> datas = groupService.selectListMapByWhere(page, qw, params);
        return Result.ok("query-ok", "查询成功").setData(datas).setTotal(page.getTotal());
    }

    @ResponseBody
    @ApiOperation(value = "考勤组表-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = Group.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addGroup(@RequestBody Group group) {
        groupService.save(group);
        return Result.ok("add-ok", "添加成功！");
    }

    @ResponseBody
    @ApiOperation(value = "考勤组表-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delGroup(@RequestBody Group group) {
        groupService.removeById(group);
        return Result.ok("del-ok", "删除成功！");
    }

    @ResponseBody
    @ApiOperation(value = "考勤组表-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = Group.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editGroup(@RequestBody Group group) {
        groupService.updateById(group);
        return Result.ok("edit-ok", "修改成功！");
    }

    @ResponseBody
    @ApiOperation(value = "考勤组表-批量修改某些字段", notes = "")
    @ApiEntityParams(value = Group.class, props = {}, remark = "考勤组表", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = Group.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        groupService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @ResponseBody
    @ApiOperation(value = "考勤组表-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelGroup(@RequestBody List<Group> groups) {
        User user = LoginUtils.getCurrentUserInfo();
        if (groups.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<Group> datasDb = groupService.listByIds(groups.stream().map(i -> i.getId()).collect(Collectors.toList()));

        List<Group> can = new ArrayList<>();
        List<Group> no = new ArrayList<>();
        for (Group data : datasDb) {
            if (true) {
                can.add(data);
            } else {
                no.add(data);
            }
        }
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            groupService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }

        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ResponseBody
    @ApiOperation(value = "考勤组表-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = Group.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(Group group) {
        Group data = (Group) groupService.getById(group);
        return Result.ok().setData(data);
    }

}
